package net.callback;

import android.os.Handler;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ui.LatteLoader;
import ui.LoaderStyle;

/**
 * Created by wzp on 2019/2/24 0024.
 * <p>
 * 描述  ：todo
 */

public class RequstCallbacks implements Callback<String> {

    private final IRequest iRequest;
    private final IFailure iFailure;
    private final ISuccess iSuccess;
    private final IError iError;
    private final LoaderStyle LOADER_STYLE;
    //静态防止内存泄漏
    private static final Handler handler = new Handler();

    public RequstCallbacks(IRequest request, IFailure failure, ISuccess success, IError error, LoaderStyle style) {
        this.iRequest = request;
        this.iFailure = failure;
        this.iSuccess = success;
        this.iError = error;
        this.LOADER_STYLE = style;

    }

    @Override
    public void onResponse(Call<String> call, Response<String> response) {
        if (response.isSuccessful()) {
            if (call.isExecuted()) {
                if (iSuccess != null) {
                    iSuccess.onSuccess(response.body());
                }
            } else {
                if (iError != null) {
                    iError.onError(response.code(), response.message());
                }
            }
        }

        stopLoader();
    }

    private void stopLoader() {
        if (LOADER_STYLE != null) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    LatteLoader.stopLoading();
                }
            },1000);

        }
    }

    @Override
    public void onFailure(Call<String> call, Throwable t) {
        if (iFailure != null) {
            iFailure.onFailure();
        }
        if (iRequest != null) {
            iRequest.onRequestEnd();
        }

        stopLoader();

    }


}
